<?php
set_time_limit(600);
ini_set('memory_limit','1024M');
require_once(__DIR__.'/vendor/autoload.php');
function error($msg){
    echo <<<EOF
<html>     
<head>     
<meta http-equiv="refresh" content="1;url=index.html">     
</head>     
<body>   
{$msg}
</body>  
</html>
EOF;
    exit;

}
$allow_types = ['zip'];
$arr = explode('.', $_FILES["file"]['name']);
$ext = end($arr);
if(!in_array($ext,$allow_types)){
   error('文件类型非法：'.$ext.' 支持:'.implode(',',$allow_types));
}
$out_file = __DIR__. "/upload/files.zip";
if(is_file($out_file)){
    unlink($out_file);
}
//move_uploaded_file($_FILES["file"]["tmp_name"], __DIR__. "/upload/upload.zip");
$zip = new ZipArchive;
$res = $zip->open($_FILES["file"]["tmp_name"]);
//解压缩到文件夹
$in_dir = __DIR__. "/upload/files";
if ($res === TRUE) {
    $zip->extractTo($in_dir);
    $zip->close();
} else {
    error('解压错误:' . $res);
}



//压缩

$zip = new ZipArchive;
if ($zip->open($out_file, ZIPARCHIVE::CREATE)!==TRUE) {
    error("cannot open <$out_file>\n");
}
$f = new \Util\FileBrowser();

//处理并加入压缩文件
if($_POST['type'] == 'tinypng'){
    echo "tinypng<br>";
    $api = new Util\TinyPNG('nvDFljsXS12aVdT1Gk2yHEF0DIJ0ZK7f');
    $f->browser($in_dir,function ($file,  $is_file, $file_type)use($factory,$zip,$in_dir,$api){
        if($file_type=='png'){
            $api->shrink($file);
            $result =json_decode($api->getResult(),true) ;
            $png = file_get_contents($result['output']['url']);
            file_put_contents($file,$png);
            $zip->addFile($file,substr($file,strlen($in_dir)));
        }
    });
}elseif(in_array($_POST['type'],['png','pngquant', 'optipng', 'pngcrush', 'pngout',])){
    echo "{$_POST['type']}<br>";

    $factory  =  new  \ImageOptimizer\OptimizerFactory();
    $f->browser($in_dir,function ($file,  $is_file, $file_type)use($factory,$zip,$in_dir){
        if($file_type=='png'){
            $optimizer = $factory ->get($_POST['type']);
            $optimizer->optimize($file);
            $zip->addFile($file,substr($file,strlen($in_dir)));
        }
    });
}

$zip->close();


/*
 $f = new \Util\FileBrowser();
$api= new Util\TinyPNG('nvDFljsXS12aVdT1Gk2yHEF0DIJ0ZK7f');
$f->browser(__DIR__.'/input',function ($file,  $is_file, $file_type)use($api){
    if($file_type=='png'){
        $newfile = str_replace('input','output',$file);
        $api->shrink($file);
        $result =json_decode($api->getResult(),true) ;
        $png = file_get_contents($result['output']['url']);
        if(!is_dir(dirname($newfile))){
            mkdir(dirname($newfile));
        }
        file_put_contents($newfile,$png);
    }
});
*/
//删除文件夹
$f->deldir($in_dir);
echo "<a href='/upload/files.zip'>下载</a>";



